﻿#include "mainwindow.h"
#include "settings.h"
#include "systemtrayicon.h"


#include <QLoggingCategory>
#include <QApplication>
#include <QDir>
#include <QProcess>
#include <QTimer>
#include <QDesktopServices>
#include <QUrl>
#include <QUrlQuery>
#include <QCryptographicHash>

//定义常量
const QString MAINTAIN_TOOL_NAME = QStringLiteral("CasstimeSetup.exe");

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    loginDialog = new LoginDialog();
    trayIcon = new SystemTrayIcon(this);
    remindWidget = new RemindWidget();
    websocketServer = new WebSocketServer(this);

    settings = Settings::getInstance();

    //从配置文件中读取状态
    QString username = settings->getUsername();
    QString password = settings->getPassword();
    bool isRemember = settings->getRememberState();

    loginDialog->setDefaultInput(username,password,isRemember);

    connect(loginDialog,SIGNAL(readyToLogin(QString,QString,bool)),this,SLOT(login(QString,QString,bool)));

    connect(websocketServer,SIGNAL(connectFailed(QString)),loginDialog,SLOT(showFailedMessage(QString)));
    connect(websocketServer,SIGNAL(connectFailed()),trayIcon,SLOT(hide()));

    connect(websocketServer,SIGNAL(messageRecived(QString,QString)),remindWidget,SLOT(showRemind(QString,QString)));
    connect(websocketServer,SIGNAL(updateRequest()),this,SLOT(checkUpdate()));
    connect(websocketServer,SIGNAL(connectSuccess()),loginDialog,SLOT(hide()));
    connect(websocketServer,SIGNAL(connectSuccess()),this,SLOT(checkUpdate()));
    //不显示欢迎信息
    connect(websocketServer,SIGNAL(connectSuccess()),trayIcon,SLOT(showWelcome()));

    connect(remindWidget,SIGNAL(urlClicked(QString)),this,SLOT(openUrl(QString)));

    connect(trayIcon,SIGNAL(messageClicked()),this,SLOT(clickMessage()));
    loginDialog->show();

    QTimer::singleShot(5000, this, SLOT(checkUpdate()));
}

MainWindow::~MainWindow()
{

}

void MainWindow::openUrl(QString url)
{
    qDebug()<<url;
    QString code = websocketServer->getToken();
    QString username = websocketServer->getUsername();

    qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
    qDebug()<<timestamp;
    QString result = code + username + QString::number(timestamp);
    qDebug()<<result;

    QString md5;
    QByteArray bb;
    bb = QCryptographicHash::hash(result.toLocal8Bit(),QCryptographicHash::Md5);
    md5.append(bb.toHex());

    QUrl linkUrl(url);
    QUrlQuery urlQuery(linkUrl);
    urlQuery.addQueryItem("username", username);
    urlQuery.addQueryItem("timestamp", QString::number(timestamp));
    urlQuery.addQueryItem("token", md5);

    linkUrl.setQuery(urlQuery.toString());

    QDesktopServices::openUrl(linkUrl);
}

//检查更新，如果有更新，弹出提示
void MainWindow::checkUpdate()
{
    qDebug()<<"check update..";
    QProcess checkUpdateProcess;
    checkUpdateProcess.start(maintainToolPath(),  QStringList() << "--checkupdates");

    if (!checkUpdateProcess.waitForStarted()){

        qDebug()<<checkUpdateProcess.errorString();
        return;
    }

    if (!checkUpdateProcess.waitForFinished()){
        qDebug()<<checkUpdateProcess.errorString();
        return;
    }

    QByteArray result = checkUpdateProcess.readAllStandardOutput();
    qDebug()<<result;

    if(!result.isEmpty() && result.indexOf("update")>-1){
        trayIcon->showMessage(SystemTrayIcon::UPDATE_MESSAGE, QStringLiteral("有新版本发布，点击升级!"));
    }
}

//调用维护工具，退出程序，进行升级
void MainWindow::updateSoftware()
{
    QProcess updateProcess;
    updateProcess.startDetached(maintainToolPath(),  QStringList() << "--updater");
    QApplication::quit();
}

//点击提醒消息
void MainWindow::clickMessage()
{
    qDebug()<<"msg clicked:"<<trayIcon->getCurrentMessageType();
    if(trayIcon->getCurrentMessageType() == SystemTrayIcon::UPDATE_MESSAGE){
        QProcess updateProcess;
        updateProcess.startDetached(maintainToolPath(),  QStringList() << "--updater");
        QApplication::quit();
    }
}


QString MainWindow::maintainToolPath()
{
    QDir exeDir(QApplication::applicationDirPath());
    return exeDir.absoluteFilePath(MAINTAIN_TOOL_NAME);
}


void MainWindow::showNewAppMessage()
{
    trayIcon->showMessage(SystemTrayIcon::NORMAL_MESSAGE,QStringLiteral("程序已经启动!"));
}

void MainWindow::login(const QString &username, const QString &password, bool isRemember)
{
    websocketServer->login(username,password);
    settings->setUsername(username);
    settings->setPassword(password);
    settings->setRememberState(isRemember);
}



